package com.huanzhidadi.java8inaction.chapter4;

import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * 生成斐波那契数列
 */
public class FibTest {
    public static void main(String[] args) {
        // iterate
        // fibByIterate();

        // generate
        fibByGenerate();

    }

    /**
     * iterate方式
     */
    static void fibByIterate() {
        Stream.iterate(new int[]{0, 1},
                        t -> new int[]{t[1], t[0] + t[1]})
                .limit(10)
                .forEach(t -> System.out.println(t[1]));
    }


    /**
     * generate方式
     */
    private static void fibByGenerate() {
        Supplier<Integer> fib = new Supplier<Integer>() {
            private int pre = 0;
            private int cur = 1;
            @Override
            public Integer get() {
                int curFib = this.cur;
                int nextValue = this.pre + this.cur;
                this.pre = this.cur;
                this.cur = nextValue;
                return curFib;
            }
        };
        Stream.generate(fib)
                .limit(10)
                .forEach(System.out::println);
    }

}
